#!/usr/bin/env python 3.6
# -*- coding: utf-8 -*-
# @Time      :2019/4/10
# @Author    :Tian Maohong
# @Email     :tianmaohong@bbdservice.com
# @File      :R31_EC_PaidBusinessConcCheck
# @Software  :PyCharm


'''eof
name:申请企业已结清业务中担保交易五级分类校验（关注类）
code:R31_EC_PaidBusinessConcCheck_2D
tableName:
columnName:
groups:企业征信校验
dependencies:EC_DSJ_2D
type:常用指标
datasourceType:在线指标
description:
eof'''

import json
import re
import sys
import datetime
import pandas as pd


reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']

def formatData(table_Name):
    """
    获取数据
    :param table_Name:字典keys
    :return:[{}]
    """
    try:
        data = EC_DSJ_2D["data"].get(table_Name)
        # table 不存在
        if data is None:
            return None
        # 表存在 但是为空[]
        elif data == "" or (isinstance(data, list) and len(data) == 0):
            return [{}]
        else:
            return data
    except:
        return None


def isFloat(x):
    '''
    判断x为float类型且大于等于0
    :param x:
    :return:
    '''
    try:
        if isinstance(float(x), float) and float(x) >= 0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False


def convertDataType(data_value, data_type):
    """
    数据格式转换
    :param data_value:
    :param data_type: float/int/str/date_time
    :return:
    """

    return_data = None
    data_value = str(data_value)
    # float
    if data_type == 'float':
        try:
            return_data = float(data_value) if len(data_value) >= 0 else None
        except:
            return_data = None
    # int
    elif data_type == 'int':
        try:
            return_data = int(data_value) if len(data_value) >= 0 else None
        except:
            return_data = None
    # str
    elif data_type == 'str':
        try:
            return_data = str(data_value) if len(data_value) >= 0 else None
        except:
            return_data = None
    # date_time
    elif data_type == 'date_time':
        r = re.compile(r'\D+')
        try:
            return_data = datetime.datetime.strptime(data_value, '%Y.%m.%d').strftime('%Y-%m-%d')
        except:
            try:
                return_data = datetime.datetime.strptime(data_value, '%Y-%m-%d').strftime('%Y-%m-%d')
            except:
                try:
                    return_data = datetime.datetime.strptime(data_value, '%Y/%m/%d').strftime('%Y-%m-%d')
                except:
                    try:
                        data_value = r.sub('', data_value)
                        return_data = datetime.datetime.strptime(data_value, '%Y%m%d').strftime('%Y-%m-%d')
                    except:
                        return_data = None

    return return_data


def dateFormat(time):
    import re
    import datetime
    r = re.compile(r'\D+')
    try:
        date = datetime.datetime.strptime(time, '%Y.%m.%d')
    except:
        try:
            date = datetime.datetime.strptime(time, '%Y-%m-%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y/%m/%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.datetime.strptime(tmp, '%Y%m%d')
                except:
                    date = None
    return date



def R31_EC_PaidBusinessConcCheck():
    """
    "Factor1=统计担保交易汇总信息单元·已结清担保交易汇总信息段(EB03B)-已结清担保交易汇总信息(EB03BH)·业务类型(EB03BD01)∈(1(银行承兑汇票),2(信用证),3(银行保函),9(其他)) and 资产质量分类(EB03BD02)==2(关注类)· (账户数(EB03BS02))的记录数；
    Factor2=统计担保账户信息单元·在保责任信息段(ED04B)·账户活动状态(ED04BD01)==2(已结清) and 五级分类(ED04BD02) ==“2(关注)”and 余额(ED04BJ01)>0 &基本信息段(ED04A)·担保账户类型(ED04AD01) in(G1(融资担保账户),G2(非融资担保账户),G3(支付担保账户))；
    Factor=Factor1+Factor2"
    注:企业征信内所有策略数据最长取值为5年，5年定义为报告生成日期【EA01AR01】当月（含）往前推60个月

    :return:
    """
    EAA = formatData('EAA')#报告头
    #如果没有报告头直接通过
    if EAA in null_type_list or EAA == [{}]:
        fiveyearsago = 0
    else:
        EA01 = EAA[0].get('EA01')
        if EA01 is None or EA01 in null_type_list:
            fiveyearsago =0
        else:
            EA01A=EA01[0].get("EA01A")
            if EA01A is None or EA01A in null_type_list:
                fiveyearsago =0
            else:
                try:
                    #报告生成日期
                    EA01AR01 = EA01A[0].get('EA01AR01')
                    create_date=datetime.datetime.strptime(EA01AR01[0:10], '%Y-%m-%d')
                    fiveyearsago= (create_date- pd.tseries.offsets.DateOffset(years=5)).strftime("%Y%m%d")
                except:
                    fiveyearsago = 0

    EBC = formatData('EBC')# 交易担保信息汇总
    EDB = formatData('EDB')# 担保账户信息

    # Factor1
    if EBC in null_type_list:
        Factor1 = None
    elif EBC == [{}]:
        Factor1 = 0
    else:
        EB03 = EBC[0].get("EB03")
        if EB03 is None:
            Factor1 = 0
        elif EB03 in null_type_list:
            Factor1 = None
        else:
            EB03B = EB03[0].get("EB03B")
            if EB03B in null_type_list:
                Factor1 = None
            else:
                EB03BH = EB03B[0].get("EB03BH")    # 已结清担保交易汇总
                if EB03BH is None:
                    Factor1 = 0
                elif EB03BH in null_type_list:
                    Factor1 = None
                else:
                    flag = []
                    for i in EB03BH:
                        EB03BD01 = i.get("EB03BD01")  # 业务类型
                        EB03BD02 = i.get("EB03BD02")  # 资产质量分类
                        EB03BS02 = i.get("EB03BS02")  # 账户数
                        if EB03BD01 is None or EB03BD02 is None or EB03BS02 is None:
                            flag.append(None)
                        else:
                            if convertDataType(EB03BD01, 'str') in ['1', '2', '3', '9'] and \
                                    convertDataType(EB03BD02, 'str') == '2' and isFloat(EB03BS02) and \
                                    convertDataType(EB03BS02, 'float') > 0:
                                flag.append(1)
                            else:
                                flag.append(0)
                    flag = filter(lambda x:x is not None, flag)
                    if len(flag) == 0:
                        Factor1 = None
                    else:
                        Factor1 = sum(flag)

    # Factor2
    if EDB in null_type_list:
        Factor2 = None
    elif EDB == [{}]:
        Factor2 = 0
    else:
        ED04 = EDB[0].get("ED04")          # 担保信息明细
        if ED04 is None:
            Factor2 = 0
        elif ED04 in null_type_list:
            Factor2 =None
        else:
            flag = []
            for i in ED04:
                ED04B = i.get("ED04B")
                ED04A = i.get("ED04A")
                if ED04A in null_type_list or ED04B in null_type_list:
                    flag.append(None)
                else:
                    ED04BD01 = ED04B[0].get("ED04BD01")  # 账户活动状态
                    ED04BD02 = ED04B[0].get("ED04BD02")  # 五级分类
                    ED04BJ01 = ED04B[0].get("ED04BJ01")  # 余额
                    ED04AD01 = ED04A[0].get("ED04AD01")  # 担保账户类型
                    try:
                    #开立日期
                        ED04AR01 =ED04A[0].get("ED04AR01")
                        ED04AR01=dateFormat(ED04AR01)
                        #ED04AR01=ED04AR01.strftime("%Y%m%d")
                    except:
                        ED04AR01= 0
                    if ED04BD01 is None or ED04BD02 is None or \
                            ED04BJ01 is None or ED04AD01 is None:
                        flag.append(None)
                    else:
                        if convertDataType(ED04BD01, 'str') == '2' and \
                                convertDataType(ED04BD02, 'str') == '2' and isFloat(ED04BJ01) and \
                                convertDataType(ED04BJ01, 'float') > 0 and ED04AD01 in ['G1', 'G2', 'G3'] :
                            if fiveyearsago == 0 or ED04AR01 == 0:
                                flag.append(1)
                            elif ED04AR01.strftime("%Y%m%d") >= fiveyearsago:
                                flag.append(1)
                            else:
                                flag.append(0)
                        else:
                            flag.append(0)
            flag = filter(lambda x:x is not None, flag)
            if len(flag) == 0:
                Factor2 = None
            else:
                Factor2 = sum(flag)


    if Factor1 is None and Factor2 is None:
        return u'缺失值'
    else:
        if Factor1 is None:
            Factor1 = 0
        if Factor2 is None:
            Factor2 = 0
        return Factor1 + Factor2


result = R31_EC_PaidBusinessConcCheck()


